package com.bee.剑指offer;

/**
 * 输入一个链表，输出该链表中倒数第k个结点。
 *
 * @version 1.0.0
 * @Author yong.Mr
 * @data 2021-03-13
 */
public class 链表中倒数第k个结点 {


    public static ListNode FindKthToTail(ListNode pHead, int k) {
        // write code here
        if (pHead == null || k < 0) {
            return null;
        }
        ListNode first = pHead;
        ListNode second = pHead;
        for (int i = 0; i < k; i++) {
            if (first == null) {
                return null;
            }
            first = first.next;

        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        return second;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        listNode.next = new ListNode(2);
        listNode.next.next = new ListNode(3);
        listNode.next.next.next = new ListNode(4);
        listNode.next.next.next.next = new ListNode(5);
        ListNode listNodes = FindKthToTail(listNode, 6);
        System.out.println(listNodes == null ? 0 : listNodes.val);
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}

